package com.nodecollege.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.BindVO;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryRelationVO;
import com.nodecollege.cloud.common.model.po.UpmsMember;
import com.nodecollege.cloud.common.model.po.UpmsRole;
import com.nodecollege.cloud.common.model.po.UpmsRoleMember;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.dao.mapper.UpmsMemberMapper;
import com.nodecollege.cloud.dao.mapper.UpmsRoleMapper;
import com.nodecollege.cloud.dao.mapper.UpmsRoleMemberMapper;
import com.nodecollege.cloud.service.RoleMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 角色成员关系
 *
 * @author LC
 * @date 2020/1/8 18:41
 */
@Service
public class RoleMemberServiceImpl implements RoleMemberService {

    @Autowired
    private UpmsRoleMemberMapper upmsRoleMemberMapper;

    @Autowired
    private UpmsRoleMapper upmsRoleMapper;

    @Autowired
    private UpmsMemberMapper upmsMemberMapper;

    /**
     * 根据人员信息查询角色列表
     *
     * @param query
     * @return
     */
    @Override
    public NCResult<UpmsRole> getRoleListByMemberId(QueryRelationVO<UpmsRole, UpmsMember> query) {
        NCUtils.nullOrEmptyThrow(query.getEndNode().getMemberId(), new UpmsException("", "成员id不能为空！"));
        List<UpmsRole> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(query.getPageSize())) {
            list = upmsRoleMapper.selectRoleListJoinRoleMember(query.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
            if (query.isSort()) {
                page.setOrderBy(query.getSortKey() + " " + query.getSortDirection());
            }
            list = upmsRoleMapper.selectRoleListJoinRoleMember(query.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 根据角色信息获取人员列表
     *
     * @param query
     * @return
     */
    @Override
    public NCResult<UpmsMember> getMemberListByRoleId(QueryRelationVO<UpmsRole, UpmsMember> query) {
        NCUtils.nullOrEmptyThrow(query.getStartNode().getRoleId(), new UpmsException("", "角色id不能为空！"));
        List<UpmsMember> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(query.getPageSize())) {
            list = upmsMemberMapper.selectMemberListJoinRoleMember(query.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
            if (query.isSort()) {
                page.setOrderBy(query.getSortKey() + " " + query.getSortDirection());
            }
            list = upmsMemberMapper.selectMemberListJoinRoleMember(query.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 绑定角色成员关系
     *
     * @param bindVO
     */
    @Override
    public NCResult bindRoleMember(BindVO bindVO) {
        NCUtils.nullOrEmptyThrow(bindVO.getMainSource(), new UpmsException("-1", "参数错误！"));

        // 最终保留的数据
        List<UpmsRoleMember> endList = new ArrayList<>();
        UpmsRoleMember query = new UpmsRoleMember();
        query.setTenantId(bindVO.getTenantId());
        if (bindVO.getMainSource()) {
            NCUtils.nullOrEmptyThrow(bindVO.getSourceIds(), new UpmsException("", "绑定入参有误!"));
            query.setRoleId(bindVO.getSourceIds().get(0));
            bindVO.getSourceIds().forEach(orgId -> {
                bindVO.getTargetIds().forEach(memberId -> {
                    UpmsRoleMember end = new UpmsRoleMember();
                    end.setMemberId(memberId);
                    end.setRoleId(orgId);
                    end.setTenantId(bindVO.getTenantId());
                    end.setState(NCConstants.INT_1);
                    endList.add(end);
                });
            });
        } else {
            NCUtils.nullOrEmptyThrow(bindVO.getTargetIds(), new UpmsException("", "绑定入参有误!"));
            query.setMemberId(bindVO.getTargetIds().get(0));
            bindVO.getTargetIds().forEach(memberId -> {
                bindVO.getSourceIds().forEach(orgId -> {
                    UpmsRoleMember end = new UpmsRoleMember();
                    end.setMemberId(memberId);
                    end.setRoleId(orgId);
                    end.setTenantId(bindVO.getTenantId());
                    end.setState(NCConstants.INT_1);
                    endList.add(end);
                });
            });
        }

        // 已绑定的数据
        List<UpmsRoleMember> exList = upmsRoleMemberMapper.selectListByRoleMember(query);

        // 取消绑定的数据
//        exList.forEach(ex -> {
//            Boolean delFlag = true;
//            for (int i = 0; i < endList.size(); i++) {
//                if (ex.getRoleId().equals(endList.get(i).getRoleId())
//                        && ex.getMemberId().equals(endList.get(i).getMemberId())) {
//                    delFlag = false;
//                    break;
//                }
//            }
//            if (delFlag) {
//                upmsRoleMemberMapper.deleteByPrimaryKey(ex.getRoleMemberId());
//            }
//        });
        AtomicInteger newBindSize = new AtomicInteger();
        AtomicInteger oldBindSize = new AtomicInteger();
        // 新增绑定的数据
        endList.forEach(end -> {
            Boolean addFlag = true;
            for (int i = 0; i < exList.size(); i++) {
                if (end.getRoleId().equals(exList.get(i).getRoleId())
                        && end.getMemberId().equals(exList.get(i).getMemberId())) {
                    addFlag = false;
                    break;
                }
            }
            if (addFlag) {
                upmsRoleMemberMapper.insert(end);
                newBindSize.getAndIncrement();
            } else {
                oldBindSize.getAndIncrement();
            }
        });
        String message = "新增绑定 " + newBindSize.toString() + "条";
        if (oldBindSize.toString().compareTo("0") > 0) {
            message = message + ", 历史已绑定 " + oldBindSize.toString() + "条";
        }
        return NCResult.ok(message);
    }

    /**
     * 解除绑定关系
     *
     * @param roleMember
     */
    @Override
    public void unBindRoleMember(UpmsRoleMember roleMember) {
        NCUtils.nullOrEmptyThrow(roleMember.getTenantId(), new UpmsException("", "租户id不能为空！"));
        NCUtils.nullOrEmptyThrow(roleMember.getRoleId(), new UpmsException("", "角色id不能为空！"));
        NCUtils.nullOrEmptyThrow(roleMember.getMemberId(), new UpmsException("", "成员id不能为空！"));
        List<UpmsRoleMember> exList = upmsRoleMemberMapper.selectListByRoleMember(roleMember);
        NCUtils.nullOrEmptyThrow(exList, new UpmsException("", "绑定关系不存在！"));
        if (exList.get(0).getState() == NCConstants.INT_0) {
            throw new UpmsException("", "该绑定关系不能解除！");
        }
        upmsRoleMemberMapper.deleteByPrimaryKey(exList.get(0).getRoleMemberId());
    }
}
